package m_router

import (
	"accx/appFramework/m_config"
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"

	"runtime/debug"
)

func NewRouter(routes Routes) *gin.Engine {
	gin.SetMode(gin.ReleaseMode)
	router := gin.New()
	path := m_config.GetConfigInstance().HttpAccessLogPath
	file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		seelog.Error("Create|Open gin output m_log file failed!")
	}
	gin.DefaultWriter = io.MultiWriter(file)
	router.Use(gin.Logger(), gin.Recovery())
	for _, route := range routes {
		switch route.Method {
		case http.MethodGet:
			router.GET(route.Pattern, route.HandlerFunc)
		case http.MethodPost:
			router.POST(route.Pattern, route.HandlerFunc)
		case http.MethodPut:
			router.PUT(route.Pattern, route.HandlerFunc)
		case http.MethodDelete:
			router.DELETE(route.Pattern, route.HandlerFunc)
		}
	}

	return router
}

func Recover(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			seelog.Debug("catch error: ", r)
			debug.PrintStack()
			c.JSON(500, gin.H{"msg": r})
		}
	}()
	c.Next()
}
